package com.uduemc.security.controller;

import java.util.concurrent.Callable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import com.uduemc.security.queue.TaskQueue;

@RestController
public class OrderController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 使用 Callable 的方式
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/order/{id:\\d+}")
	public Callable<Integer> order(@PathVariable Integer id) {
		logger.info("主线程开始");
		Callable<Integer> result = new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {
				logger.info("副线程开始");
				Thread.sleep(1000);
				logger.info("副线程开始");
				return id;
			}
		};
		logger.info("主线程返回");
		return result;
	}

	@Autowired
	private TaskQueue taskQueue;
	
	/**
	 * 使用 DeferredResult
	 * @throws InterruptedException 
	 */
	@GetMapping("/order2/{id:\\d+}")
	public DeferredResult<Integer> order2(@PathVariable Integer id) throws InterruptedException {
		logger.info("主线程开始");
		// 定义超时时间
		long outOfTime = 10000L;
		// 超时返回的结果
		Integer outOfTimeResult = 400;
		DeferredResult<Integer> result = new DeferredResult<>(outOfTime, outOfTimeResult);

		result.onTimeout(() -> {
			logger.info("主线程: onTimeout");
		});

		result.onCompletion(() -> {
			logger.info("主线程: onCompletion");
		});
		logger.info("主线程返回");
		
		// 加入队列中
		taskQueue.offer(result);
		
		return result;
	}
}
